package com.jinxin.platform.cdflowchart.controller;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdflowchart.pojo.domains.CdcomdataTableInfoInfoDO;
import com.jinxin.platform.cdflowchart.pojo.domains.CdflowchartBeeTreeInfoDO;
import com.jinxin.platform.cdflowchart.service.CdcomdataTableInfoService;
import com.jinxin.platform.cdflowchart.service.CdflowchartBeeTreeService;
import com.jinxin.platform.cdflowchart.util.CdflowchartBuildBeeTreeUtil;
import com.jinxin.platform.cdflowchart.util.GenerateID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.AbstractLinkedList;
import org.apache.logging.log4j.util.Strings;
import org.checkerframework.checker.units.qual.A;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import springfox.documentation.spring.web.json.Json;

import java.util.*;

/**
 * 能耗树(CdflowchartBeeTree)表控制层
 *
 * @author cxiaojiang
 * @since 2021-10-13 09:38:52
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/cdflowchartBeeTree")
@Api(tags = {"能耗"}, description = "能耗树相关接口")
public class BeeTreeController {

    /**
     * 服务对象
     */
    @Autowired
    private CdflowchartBeeTreeService cdflowchartBeeTreeService;

    @Autowired
    private CdcomdataTableInfoService cdcomdataTableInfoService;


    /**
     * 获取能耗组织树
     * @return
     * @throws Exception
     */
    @GetMapping("/getBeeTree")
    @ApiOperation(value="获取能耗组织树", httpMethod = "GET", notes="获取能耗组织树")
    public JsonResult getItemTree() throws Exception {
        List<CdflowchartBeeTreeInfoDO> cdflowchartBeeTreeInfoDOS = cdflowchartBeeTreeService.queryAll(new CdflowchartBeeTreeInfoDO());
        //log.info("能耗树-数据源：{}", cdflowchartBeeTreeInfoDOS);
        List<CdflowchartBeeTreeInfoDO> tree = CdflowchartBuildBeeTreeUtil.getTree(cdflowchartBeeTreeInfoDOS, "id");
        return JsonResult.ok(tree);
    }


    /**
     * 新增编辑节点
     * @param cdflowchartBeeTreeInfoDO
     * @return
     */
    @PostMapping("/insertAndEdit")
    @ApiOperation(value="新增编辑节点", httpMethod = "POST", notes="新增编辑节点")
    public JsonResult insertAndEdit(@RequestBody CdflowchartBeeTreeInfoDO cdflowchartBeeTreeInfoDO) {
        log.info("--------------"+cdflowchartBeeTreeInfoDO);
        String upNodeId = cdflowchartBeeTreeInfoDO.getUpNodeId();
        String upNodeLevel = cdflowchartBeeTreeInfoDO.getUpNodeLevel();
        if (Strings.isBlank(cdflowchartBeeTreeInfoDO.getId())) {
            // 新增节点
            if (Strings.isBlank(upNodeId)) {
                // 一级节点，同时判断是否是能耗点（能耗点可以绑定设备）
                if (Strings.isBlank(cdflowchartBeeTreeInfoDO.getBindDevicesName())) {
                    // 文件夹、有孩子节点
                    cdflowchartBeeTreeInfoDO.setIsChildren("2");
                } else {
                    // 文件、无孩子节点
                    cdflowchartBeeTreeInfoDO.setIsChildren("1");
                }
                cdflowchartBeeTreeInfoDO.setId(GenerateID.generateUUID());
                cdflowchartBeeTreeInfoDO.setNodeLevel("1");
                cdflowchartBeeTreeInfoDO.setIsParent("1");
                cdflowchartBeeTreeInfoDO.setCreatedTime(new Date());
                cdflowchartBeeTreeService.insertSomeOne(cdflowchartBeeTreeInfoDO);
                log.info("新增一级节点：{}", cdflowchartBeeTreeInfoDO);
            } else {
                // （二）级节点，同时判断是否是能耗点（能耗点可以绑定设备）
                if (Strings.isBlank(cdflowchartBeeTreeInfoDO.getBindDevicesName())) {
                    cdflowchartBeeTreeInfoDO.setIsChildren("2");
                } else {
                    cdflowchartBeeTreeInfoDO.setIsChildren("1");
                }
                cdflowchartBeeTreeInfoDO.setId(GenerateID.generateUUID());
                cdflowchartBeeTreeInfoDO.setNodeLevel(String.valueOf(Integer.parseInt(upNodeLevel)+1));
                cdflowchartBeeTreeInfoDO.setIsParent("2");
                cdflowchartBeeTreeInfoDO.setCreatedTime(new Date());
                // 新建三级节点时，同时要继承上级节点的设备类型，从二级节点开始有知道设备类型
                CdflowchartBeeTreeInfoDO upBeeTreeInfoDO = cdflowchartBeeTreeService.queryById(upNodeId);
                if (Integer.parseInt(upNodeLevel)+1 >= 3) {
                    cdflowchartBeeTreeInfoDO.setDeviceType(upBeeTreeInfoDO.getDeviceType());
                }
                cdflowchartBeeTreeService.insertSomeOne(cdflowchartBeeTreeInfoDO);
                log.info("新增（二）级节点：{}", cdflowchartBeeTreeInfoDO);
                log.info("新增（二）级节点：{}", cdflowchartBeeTreeInfoDO);
                log.info("新增（二）级节点：{}", cdflowchartBeeTreeInfoDO);
            }
        } else {
            // 编辑节点数据
            cdflowchartBeeTreeInfoDO.setUpdatedTime(new Date());
            cdflowchartBeeTreeInfoDO.setNodeLevel(String.valueOf(Integer.parseInt(upNodeLevel)+1));
            cdflowchartBeeTreeService.update(cdflowchartBeeTreeInfoDO);
            log.info("编辑节点：{}", cdflowchartBeeTreeInfoDO);
        }
        return JsonResult.ok();
    }


    /**
     * 获取上级节点
     */
    @GetMapping("/getUpNodes")
    @ApiOperation(value="获取上级节点", httpMethod = "GET", notes="获取上级节点")
    public JsonResult getUpNodes() {
        CdflowchartBeeTreeInfoDO cdflowchartBeeTreeInfoDO = new CdflowchartBeeTreeInfoDO();
        // 新建节点时，绑定了设备的即为叶子节点（无孩子节点），否则为上级节点（有孩子节点）
        cdflowchartBeeTreeInfoDO.setIsChildren("2");
        List<CdflowchartBeeTreeInfoDO> treeInfoDOS = cdflowchartBeeTreeService.queryAll(cdflowchartBeeTreeInfoDO);
        List<Map<String,String>> list = new ArrayList<>();
        for (CdflowchartBeeTreeInfoDO infoDO : treeInfoDOS) {
            Map<String,String> map = new HashMap<>();
            map.put("name", infoDO.getNodeName());
            map.put("value", infoDO.getId());
            map.put("level", infoDO.getNodeLevel());
            map.put("deviceType", infoDO.getDeviceType());
            list.add(map);
        }
        return JsonResult.ok(list);
    }


    /**
     * 根据类型获取设备
     */
    @GetMapping("/getDevices")
    @ApiOperation(value="根据类型获取设备", httpMethod = "GET", notes="根据类型获取设备")
    public JsonResult getDevices(@RequestParam("deviceType") String deviceType) {
        CdcomdataTableInfoInfoDO tableInfoInfoDO = new CdcomdataTableInfoInfoDO();
        tableInfoInfoDO.setField01(deviceType);
        List<CdcomdataTableInfoInfoDO> infoInfoDOS = cdcomdataTableInfoService.queryAll(tableInfoInfoDO);
        List<Map<String,String>> list = new ArrayList<>();
        for (CdcomdataTableInfoInfoDO infoInfoDO : infoInfoDOS) {
            Map<String, String> map = new HashMap<>();
            map.put("name", infoInfoDO.getField02());
            map.put("value", infoInfoDO.getField14());
            list.add(map);
        }
        return JsonResult.ok(list);
    }


    /**
     * 删除节点数据
     */
    @GetMapping("/delete")
    @ApiOperation(value="删除节点数据", httpMethod = "GET", notes="删除节点数据")
    public JsonResult delete(@RequestParam("id") String id) {
        CdflowchartBeeTreeInfoDO beeTreeInfoDO1 = cdflowchartBeeTreeService.queryById(id);
        if ("1".equals(beeTreeInfoDO1.getNodeType())) {
            // 1 为文件夹，需要递归遍历删除，若为2，则是文件可直接删除
            CdflowchartBeeTreeInfoDO beeTreeInfoDO2 = new CdflowchartBeeTreeInfoDO();
            beeTreeInfoDO2.setUpNodeId(beeTreeInfoDO1.getId());
            List<CdflowchartBeeTreeInfoDO> treeInfoDOS2 = cdflowchartBeeTreeService.queryAll(beeTreeInfoDO2);
            for (CdflowchartBeeTreeInfoDO infoDO2 : treeInfoDOS2) {
                CdflowchartBeeTreeInfoDO beeTreeInfoDO3 = new CdflowchartBeeTreeInfoDO();
                beeTreeInfoDO3.setUpNodeId(infoDO2.getId());
                List<CdflowchartBeeTreeInfoDO> treeInfoDOS3 = cdflowchartBeeTreeService.queryAll(beeTreeInfoDO3);
                // 加个判断，不用每次都递归遍历五次
                if (treeInfoDOS3.size() > 0) {
                    for (CdflowchartBeeTreeInfoDO infoDO3 : treeInfoDOS3) {
                        CdflowchartBeeTreeInfoDO beeTreeInfoDO4 = new CdflowchartBeeTreeInfoDO();
                        beeTreeInfoDO4.setUpNodeId(infoDO3.getId());
                        List<CdflowchartBeeTreeInfoDO> treeInfoDOS4 = cdflowchartBeeTreeService.queryAll(beeTreeInfoDO4);
                        for (CdflowchartBeeTreeInfoDO infoDO4 : treeInfoDOS4) {
                            CdflowchartBeeTreeInfoDO beeTreeInfoDO5 = new CdflowchartBeeTreeInfoDO();
                            beeTreeInfoDO5.setUpNodeId(infoDO4.getId());
                            List<CdflowchartBeeTreeInfoDO> treeInfoDOS5 = cdflowchartBeeTreeService.queryAll(beeTreeInfoDO4);
                            for (CdflowchartBeeTreeInfoDO infoDO5 : treeInfoDOS5) {
                                cdflowchartBeeTreeService.deleteById(infoDO5.getId());
                            }
                            cdflowchartBeeTreeService.deleteById(infoDO4.getId());
                        }
                        cdflowchartBeeTreeService.deleteById(infoDO3.getId());
                    }
                }
                cdflowchartBeeTreeService.deleteById(infoDO2.getId());
            }
            cdflowchartBeeTreeService.deleteById(beeTreeInfoDO1.getId());
        }
        cdflowchartBeeTreeService.deleteById(beeTreeInfoDO1.getId());
        return JsonResult.ok();
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public CdflowchartBeeTreeInfoDO selectOne(String id) {
        return cdflowchartBeeTreeService.queryById(id);
    }


    /**
     * 查询所有数据，分页
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return
     */
    //@ApiOperation(value="分页查询所有数据",httpMethod = "GET" ,notes="无条件查询所有数据，分页")
    @GetMapping("/queryAllByLimit")
    public List<CdflowchartBeeTreeInfoDO> queryAllByLimit(@RequestParam("offset") int offset, @RequestParam("limit") int limit) {
        return cdflowchartBeeTreeService.queryAllByLimit(offset, limit);
    }


    /**
     * 动态更新数据
     *
     * @param cdflowchartBeeTreeInfoDO
     * @return
     */
    //@ApiOperation(value="动态更新所有数据",httpMethod = "POST" ,notes="注意时间的填写格式")
    @PostMapping("/update")
    public CdflowchartBeeTreeInfoDO update(@RequestBody CdflowchartBeeTreeInfoDO cdflowchartBeeTreeInfoDO) {
        return cdflowchartBeeTreeService.update(cdflowchartBeeTreeInfoDO);
    }


    /**
     * 删除单条数据
     *
     * @param id
     * @return
     */
    //@ApiOperation(value="删除单条数据",httpMethod = "POST" ,notes="只返回成功与否,true代表成功，false代表失败")
    @PostMapping("deleteById")
    public boolean deleteById(@RequestParam("id") String id) {
        return cdflowchartBeeTreeService.deleteById(id);
    }


    /**
     * 删除多条数据
     *
     * @param ids
     * @return object, 显示多少即为删除多少条
     */
    //@ApiOperation(value="删除多条数据",httpMethod = "POST" ,notes="返回多少即为删除多少条")
    @PostMapping("deleteByIds")
    public Object deleteByIds(@RequestParam("ids") List<String> ids) {
        return cdflowchartBeeTreeService.deleteByIds(ids);
    }


    /**
     * 新增数据
     *
     * @param cdflowchartBeeTreeInfoDO 实例对象
     * @return 实例对象
     */
    //@ApiOperation(value="新增数据",httpMethod = "POST" ,notes="如果插入失败则返回空值，成功则返回插入实体，更新人系统默认无")
    @PostMapping("/insert")
    public CdflowchartBeeTreeInfoDO insert(@RequestBody CdflowchartBeeTreeInfoDO cdflowchartBeeTreeInfoDO) {
        return cdflowchartBeeTreeService.insert(cdflowchartBeeTreeInfoDO);
    }

}


